<!--提货卡批次列表-->
<template>
  <div>
    <Card :bordered="false" dis-hover class="mt15 ivu-mt" :padding="0">
      <div class="new_card_pd">
        <Form ref="tableFrom" inline
              :model="tableFrom" :label-width="labelWidth"
              :label-position="labelPosition" >
          <FormItem label="提货卡类型：" label-for="status">
            <Select v-model="tableFrom.recharcard_type" placeholder="请选择" clearable @on-change="userSearchs"
                    style="width: 250px;"
            >
              <Option value="1">通用提货卡(余额)1111</Option>
              <Option value="2">商品提货卡</Option>
              <Option value="3">分类提货卡</Option>
            </Select>
          </FormItem>
          <FormItem label="是否有效：" label-for="status">
            <Select v-model="tableFrom.status" placeholder="请选择" clearable @on-change="userSearchs"
                    style="width: 250px;">
              <Option value="1">正常</Option>
              <Option value="0">未开启</Option>
            </Select>
          </FormItem>
          <FormItem label="提货卡名称：" label-for="coupon_title">
            <Input v-model="tableFrom.recharcard_title" placeholder="请输入提货卡名称" @on-search="userSearchs"
                   style="width: 250px;margin-right:14px"/>
            <Button type="primary" @click="orderSearch()" style="margin-right:14px">查询</Button>
          </FormItem>
        </Form>
      </div>
    </Card>

    <Card :bordered="false" dis-hover class="ivu-mt">
      <Button v-auth="['admin-user-recharcard-create']" type="primary" @click="add">添加提货卡</Button>
      <Button v-auth="['admin-user-recharcard-create']" style="margin-left:20px;" type="primary" @click="exportList" >下载导出</Button>
      <Table :columns="RecharcardColumns" :data="tableList" ref="table" class="ivu-mt"
             :loading="loading" highlight-row
             no-userFrom-text="暂无数据"
             no-filtered-userFrom-text="暂无筛选结果">
        <template slot-scope="{ row }" slot="recharcard_money">
          <span>{{ row.recharcard_money }}元</span>
        </template>
        <template slot-scope="{ row }" slot="recharcard_img">
          <img style="width:50px;height:50px" :src="row.recharcard_img" alt="">
        </template>

        <template slot-scope="{ row }" slot="product_cate_id">
          <span v-if="row.product_id">{{row.product_id}}</span>
          <span v-else-if="row.category_id">{{row.category_id}}</span>
          <span v-else>无商品/分类</span>
        </template>

        <template slot-scope="{ row }" slot="count">
          <span v-if="row.is_permanent">不限量</span>
          <div v-else>
            <span class="fa">发布：{{ row.total_count }}</span>
            <span class="sheng">剩余：{{ row.remain_count }}</span>
          </div>
        </template>
        <template slot-scope="{ row }" slot="recharcard_type">
          <span>{{row.recharcard_type}}123</span>
        </template>
        <template slot-scope="{ row }" slot="recharcard_title">
          <Tooltip max-width="200" placement="bottom">
            <span class="line2">{{ row.recharcard_title }}</span>
            <p slot="content">{{ row.recharcard_title }}</p>
          </Tooltip>
        </template>
        <template slot-scope="{ row }" slot="company">
          <span>{{row.company}}</span>
        </template>

        <template slot-scope="{ row }" slot="status">
          <i-switch v-model="row.status" :value="row.status" :true-value="1" :false-value="0" size="large"
                    @on-change="openChangeStatus(row)">
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
          </i-switch>
        </template>
        <template slot-scope="{ row }" slot="add_time">
          <span>{{row.add_time}}</span>
        </template>
        <template slot-scope="{ row }" slot="recharcard_rule">
          <div v-html="row.rule.title"></div>
        </template>
        <template slot-scope="{ row }" slot="action">
          <a @click="recharcardActive(row)">激活</a>
          <a @click="recharCardDelModel(row.id)" style="margin-left:10px;">删除</a>
        </template>
      </Table>
      <div class="acea-row row-right page">
        <Page :total="total" :current="tableFrom.page" show-elevator show-total @on-change="pageChange"
              :page-size="tableFrom.limit"/>
      </div>
    </Card>
    <!-- 删除模态框   -->
    <Modal
        v-model="delmodal"
        title="提示"
        @on-ok="recharCardDel"
        @on-cancel="cancel">
      <p><span style="color: red;">删除会导致该次生成的提货卡不可使用，</span><br>确定要删除吗?</p>
    </Modal>
    <!-- 激活模块   -->
    <Modal
        v-model="activeModel"
        title="提货卡批量激活"
        ok-text="立即激活"
        @on-ok="activeAll"
        @on-cancel="cancel">
      <Form :model="formData" :label-width="150">
        <p style="color: red;margin:5px;">批量激活只能激活对应批次生成的提货卡！否则无法批量激活</p>
        <FormItem label="购买单位名称">
          <Input
              v-model="formData.use_company"
              v-width="320"
              placeholder="请输入购买单位名称"
          ></Input>
        </FormItem>
        <FormItem label="激活卡编号区间">
          <Input
              v-model="formData.start_card_no"
              v-width="140"
              placeholder="请输入激活卡开始编号"
          ></Input>
          ——
          <Input
              v-model="formData.end_card_no"
              v-width="140"
              placeholder="请输入激活卡结束编号"
          ></Input>
          <br>
          <span style="color:red;">激活卡编号请输入带NO.的完整卡编号,Eg:"NO.2022000014"</span>
          <br>
          <span style="color:red;">可到提货卡生成记录页面复制完整卡编号</span>
        </FormItem>
        <FormItem label="有效期">
          <RadioGroup v-model="formData.recharcard_use_type" @on-change="change">
            <Radio :label="1">天数</Radio>
            <Radio :label="2">时间段</Radio>
          </RadioGroup>
        </FormItem>

        <FormItem v-show="formData.recharcard_use_type == 1" >
          <InputNumber
              :min="1"
              :max="100000000"
              v-model="formData.recharcard_use_time"
          ></InputNumber>
          <div class="info">激活后多少天内有效</div>
        </FormItem>

        <FormItem v-show="formData.recharcard_use_type == 2"  >
          <DatePicker
              v-width="320"
              :editable="false"
              v-model="time"
              type="datetimerange"
              placeholder="激活后在这个时间段内可以使用"
              @on-change="dateChange"
          ></DatePicker>
        </FormItem>

      </Form>
    </Modal>
  </div>
</template>

<script>
import {createDeleat,recharCardList,openChangeStatus,receiveRuler,recharcardActivateLst,storeRecharcard,recharCardDel} from '@/api/user.js'
import {mapState} from "vuex";
import exportExcel from "@/utils/newToExcel.js";
export default {
  name: "list.vue",
  data() {
    return {
      activeModel: false,  // 激活弹窗模态框
      delmodal:false,
      id:0,
      rowId:0,  // 提货卡批次ID
      formData: {
        use_company:'',
        start_card_no:'',
        end_card_no:'',
        recharcard_use_type:1,
        recharcard_use_time:'',
      },
      labelShow:false,
      loading: false,
      recharcard_rule:'',
      RecharcardColumns: [
        {
          title: "ID",
          key: "id",
          align:'center',
          width: 80
        },
        {
          title: "提货卡封面",
          slot: "recharcard_img",
          align:'center',
          minWidth: 80
        },
        {
          title: "提货卡名称",
          slot: "recharcard_title",
          align:'center',
          minWidth: 100
        },
        {
          title: "提货卡类型",
          slot: "recharcard_type",
          align:'center',
          minWidth: 80
        },
        {
          title: "购买单位名称",
          slot: "company",
          align:'center',
          minWidth: 80
        },
        {
          title: "面值",
          slot: "recharcard_money",
          align:'center',
          minWidth: 100
        },
        {
          title: "商品/分类ID",
          slot: "product_cate_id",
          align:'center',
          minWidth: 100
        },
        {
          title: "添加时间",
          slot: "add_time",
          align:'center',
          minWidth: 180
        },
        {
          title: "发布数量",
          slot: "count",
          align:'center',
          minWidth: 90
        },
        {
          title: "是否开启",
          slot: "status",
          align:'center',
          minWidth: 90
        },
        {
          title: "使用规则",
          slot: "recharcard_rule",
          align:'center',
          minWidth: 90
        },
        {
          title: "操作",
          slot: "action",
          fixed: "right",
          align:'center',
          minWidth: 200
        }
      ],
      tableFrom: {
        status: "",
        recharcard_title: "",
        recharcard_type: "",
        page: 1,
        limit: 15
      },
      time:[],
      tableList: [],
      total: 0,
      receiveList: [],
      rows: {},
      rouler:[]
    };
  },
  created(){
    this.receiveRuler()
  },
  computed: {
    ...mapState("admin/layout", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? undefined : 96;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    }
  },
  methods:{
    //下载导出
    async exportList(){
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let excelData = JSON.parse(JSON.stringify(this.tableFrom));
      excelData.page = 1;
      excelData.product_id= this.$route.query.product_id || "";
      for (let i = 0; i < excelData.page + 1; i++) {
        let lebData = await this.storeRecharcard(excelData);
        if (!fileName) fileName = lebData.filename;
        if (!filekey.length) {
          filekey = lebData.filekey;
        }
        if (!th.length) th = lebData.header;
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        }
      }
      exportExcel(th, filekey, fileName, data);
    },
    storeRecharcard(excelData){
      return new Promise((resolve, reject) => {
        storeRecharcard(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },
    //点击激活按钮后的提交
    activeAll(){
      console.log("this.formData== ",this.formData)
      recharcardActivateLst(this.rowId,this.formData).then(res=>{
        this.disabled = true;
        this.$Message.success(res.msg);
        setTimeout(() => {
          this.$router.push({
            path: "/admin/user/recharcard/record",
          });
        }, 1000);
      })
          .catch((err) => {
            this.$Message.error(err.msg);
          });
    },
    /**
     * 获取提货卡规则
     */
    receiveRuler(){
      receiveRuler().then(res=>{
        this.rouler = res.data
        this.recharCardList();
      })
    },
    //提货卡点击开启关闭
    openChangeStatus(row){
      var data = {
        status : row.status
      }
      openChangeStatus(row.id,data).then(res=>{
        this.$Message.success(res.msg);
      })
      .catch((err) => {
        this.$Message.error(err.msg);
      });
    },
    //提货卡点击激活
    recharcardActive(row){
      this.rowId = row.id
      this.activeModel = true
    },
    cancel(){
      this.delmodal = false
      this.activeModel = false
    },
    //点击调用删除提货卡弹窗
    recharCardDelModel(id){
      this.id = id
      this.delmodal = true
    },
    recharCardDel(id){
      recharCardDel(this.id).then(res=>{
        this.$Message.success(res.msg);
        this.delmodal = false
        this.recharCardList() // 局部刷新提货卡列表
      })
      .catch((err) => {
        this.$Message.error(err.msg);
      });
    },
    //添加提货卡
    add() {
      this.$router.push({path: "/admin/user/recharcard/create"});
    },
    /**
     * 提货卡列表获取方法
     */
    recharCardList(){
      recharCardList(this.tableFrom).then(res=>{
        this.tableList = res.data.list
        this.total = res.data.count
      })
          .catch((err) => {
            this.$Message.error(err.msg);
          });
    },
    // change(){
    //   console.log('cccccccccc')
    //   this.time = []
    //   this.formData.recharcard_use_time = ''
    // },
    pageChange(index) {
      this.tableFrom.page = index;
      this.recharCardList();
    },
    // 表格搜索
    userSearchs() {
      this.tableFrom.page = 1;
      this.recharCardList();
    },
    orderSearch(){
      this.recharCardList()
    },
    //补零
    fillZero (str) {
      var realNum;
      if (str < 10) {
        realNum = '0' + str;
      } else {
        realNum = str;
      }
      return realNum;
    },
    getNowTime(time) {
      let now = new Date(time);
      let year = now.getFullYear(); //获取完整的年份(4位,1970-????)
      let month = now.getMonth() + 1; //获取当前月份(0-11,0代表1月)
      let today = now.getDate(); //获取当前日(1-31)
      let hour = now.getHours(); //获取当前小时数(0-23)
      let minute = now.getMinutes(); //获取当前分钟数(0-59)
      let second = now.getSeconds(); //获取当前秒数(0-59)
      let nowTime = ''
      nowTime = year + '/' + this.fillZero(month) + '/' + this.fillZero(today) + ' ' + this.fillZero(hour) + ':' +
          this.fillZero(minute) + ':' + this.fillZero(second)
      return nowTime
    },
    /**
     * 处理时间日期
     * @param time
     */
    dateChange(time) {
      // this.formData.recharcard_use_time = time[0] + ' —— ' + time[1]
      var date1 = this.getNowTime(time[0])
      var date2 = this.getNowTime(time[1])
      if(new Date(time[0]).getTime() == new Date(time[1]).getTime()){
        this.time = []
        return this.$Message.error("所选时间不能相同");
      }
      if(new Date(time[0]).getTime() > new Date(time[1]).getTime()){
        this.formData.recharcard_use_time = date2 + '-' + date1
      }else{
        this.formData.recharcard_use_time = date1 + '-' + date2
      }
    },
  }
}
</script>


<style scoped lang="stylus">
.fa {
  color: #0a6aa1;
  display: block;
}

.sheng {
  color: #ff0000;
  display: block;
}

.tabBox_img {
  width: 36px;
  height: 36px;
  border-radius: 4px;
  cursor: pointer;
}
img {
  width: 100%;
  height: 100%;
}

</style>
